package com.duowan.cms.filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.webapp.content.SpringApplicationContextHolder;
import com.duowan.cms.common.webapp.property.ExtendedPropertyPlaceholderConfigurer.PropertiesHolder;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.dto.user.PowerInfo;
import com.duowan.cms.dto.user.UserInfo;
import com.duowan.cms.service.user.PowerService;
import com.duowan.cms.service.user.UserService;

public class AuthorizationFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
				throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url =  request.getRequestURI();
        if (url.indexOf(".") > 0) {
			url = url.substring(0, url.indexOf("."));
		}
        UserInfo userInfo = (UserInfo)request.getSession().getAttribute("userInfo");
        ChannelInfo channelInfo = (ChannelInfo)request.getSession().getAttribute("channelInfo");
       
        String powerId = PropertiesHolder.get(url);
        if (!StringUtil.isEmpty(powerId)) {
            boolean hasPower = getUserService().hasPower(channelInfo.getId(), userInfo ,powerId);
            if (!hasPower) {
            	PowerInfo powerInfo = getPowerService().getById(powerId);
               response.sendRedirect("/toErrorPage.do?errorMessage="  +URLEncoder.encode("你没有操作["+powerInfo.getName()+"]权限","UTF-8"));
               return;
    		}
		}

        filterChain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

	private UserService getUserService(){
		return SpringApplicationContextHolder.getBean("userService", UserService.class);
	}
	
	private PowerService getPowerService(){
		return SpringApplicationContextHolder.getBean("powerService", PowerService.class);
	}
}
